package com.crane.oss.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.BizException;
import com.crane.common.core.exception.SysException;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.sys.bean.request.dict.AddDictReq;
import com.crane.oss.sys.bean.request.dict.UpdateDictReq;
import com.crane.oss.sys.bean.request.dict.QueryDictReq;
import com.crane.oss.sys.bean.resp.DictListResp;
import com.crane.oss.sys.bean.resp.DictResp;
import com.crane.oss.sys.dao.DictDao;
import com.crane.oss.sys.dao.DictDetailDao;
import com.crane.oss.sys.model.Dict;
import com.crane.oss.sys.model.DictDetail;
import com.crane.oss.sys.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zhenxing.pi
 * @email ccsu123456@qq.com
 */
@Service
@Slf4j
public class DictServiceImpl implements DictService {

    @Resource
    protected DictDao dictDao;

    @Resource
    protected DictDetailDao dictDetailDao;


    @Override
    public DictResp queryDict(Long id) {
        log.info(" queryDict id={}", id);
        Dict dict = dictDao.selectById(id);
        if (null == dict) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "字典");
        }
        DictResp dictResp = new DictResp();
        BeanUtil.copyProperties(dict, dictResp);
        //查询明细
//        List<DictDetail> dictDetailList = dictDetailDao.selectList(Wrappers.lambdaQuery(DictDetail.class)
//                .eq(DictDetail::getDicGroupId, id));
//        List<DictDetailResp> detailRespList = BeanUtil.copyList(dictDetailList, DictDetailResp.class);
//        dictResp.setDetailList(detailRespList);
        return dictResp;
    }

    @Override
    public IPage<DictListResp> queryList(QueryDictReq queryRequest) {
        log.info(" queryList queryRequest={}", queryRequest);
        IPage<DictListResp> result = new Page<>();
        result.setCurrent(queryRequest.getPageNo());
        result.setPages(queryRequest.getPageSize());

        LambdaQueryWrapper<Dict> queryDictWrapper = new LambdaQueryWrapper<>();
        queryDictWrapper.like(StringUtils.isNotBlank(queryRequest.getDictGroupCode()), Dict::getDictGroupCode, queryRequest.getDictGroupCode());
        queryDictWrapper.like(StringUtils.isNotBlank(queryRequest.getDictGroupName()), Dict::getDictGroupName, queryRequest.getDictGroupName());
        Page<Dict> page = new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize());
        IPage<Dict> iPage = dictDao.selectPage(page, queryDictWrapper);
        if (CollectionUtils.isEmpty(iPage.getRecords())) {
            result.setTotal(0);
            return result;
        }
        result.setTotal(iPage.getTotal());
        List<DictListResp> resultList = BeanUtil.copyList(iPage.getRecords(), DictListResp.class);
        result.setRecords(resultList);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(AddDictReq addRequest) {
        log.info(" save request={}", addRequest);
        int count = dictDao.selectCount(Wrappers.lambdaQuery(Dict.class)
                .and(s -> s.eq(Dict::getDictGroupCode, addRequest.getDictGroupCode()).
                        or().eq(Dict::getDictGroupName, addRequest.getDictGroupName())));
        if (count > 0) {
            throw new BizException("编码组已存在");
        }
        Dict adDict = new Dict();
        adDict.setCreateTime(new Date());
        BeanUtil.copyProperties(addRequest, adDict);
        int i = 0;
        try {
            i = dictDao.insert(adDict);
        } catch (Exception e) {
            log.info(" save exception={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(UpdateDictReq updateRequest) {
        log.info(" update request={}", updateRequest);
        int count = dictDao.selectCount(Wrappers.lambdaQuery(Dict.class)
                .and(s -> s.eq(Dict::getDictGroupCode, updateRequest.getDictGroupCode()).
                        or().eq(Dict::getDictGroupName, updateRequest.getDictGroupName()))
                .ne(Dict::getId, updateRequest.getId()));
        if (count > 0) {
            throw new BizException("编码组已存在");
        }
        Dict dict = new Dict();
        BeanUtil.copyProperties(updateRequest, dict);
        dict.setUpdateTime(new Date());
        int i = 0;
        try {
            i = dictDao.updateById(dict);
        } catch (Exception e) {
            log.info(" update exception={}", e);
            throw new SysException();
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.info(" delete id={}", id);
        dictDetailDao.delete(Wrappers.lambdaQuery(DictDetail.class).eq(DictDetail::getDicGroupId, id));
        return dictDao.deleteById(id);
    }

}
